

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutter_sizefit/flutter_sizefit.dart';
import 'package:flutter_xiecheng/core/extension_business/custom_print.dart';

// 携程首页可能出现的域名
const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/webapp/ccard/list?isHideNavBar=YES&bid=8&amp;amp;cid=1&amp;amp;pid=4', 'm.ctrip.com/html5/', 'm.ctrip.com/html5', 'webapp/gourmet/food/homeList/undefined', 'm.ctrip.com/webapp/hotel/forcelogin/'];

class JKWebView extends StatefulWidget {
  bool hideAppBar;
  bool backForbid;
  String icon;
  String statusBarColor;
  String title;
  String url;

  JKWebView({this.hideAppBar, this.icon, this.statusBarColor, this.title, this.url, this.backForbid = false});

  @override
  _JKWebViewState createState() => _JKWebViewState();
}

class _JKWebViewState extends State<JKWebView> {

  final webviewReference = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription<WebViewStateChanged> _onStateChanged;
  StreamSubscription<WebViewHttpError> _onHttpErrorChange;
  /// 是否返回
  bool exiting = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    webviewReference.close();
    _onUrlChanged = webviewReference.onUrlChanged.listen((event) {

    });

    _onStateChanged = webviewReference.onStateChanged.listen((WebViewStateChanged state) {
      switch (state.type) {
        case WebViewState.startLoad:
          print("💣💣💣💣💣💣💣💣:${state.url}");
          if(_isMain(state.url) && !exiting) {
            if(widget.backForbid) {
              webviewReference.launch(widget.url);
            } else {
              BoostNavigator.instance.pop();
              exiting = true;
            }
          }
          break;
        default:
          break;
      }
    });

    _onHttpErrorChange = webviewReference.onHttpError.listen((WebViewHttpError error) {
      myPrint("网页加载错误：$error", StackTrace.current);
    });
  }

  // 是否是携程首页的链接
  _isMain(String url) {
    bool contain = false;
    for(final value in CATCH_URLS) {
      if(url?.endsWith(value) ?? false) {
        contain = true;
        break;
      }
    }
    return contain;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpErrorChange.cancel();
    webviewReference.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorString = widget.statusBarColor ?? "ffffff";
    Color backButttonColor;
    if (statusBarColorString == 'ffffff') {
      backButttonColor = Colors.black;
    } else {
      backButttonColor = Colors.white;
    }
    return Scaffold(
      body: Column(
        children: [
          _appbar(Color(int.parse('0xff' + statusBarColorString)), backButttonColor),
          Expanded(
              child: WebviewScaffold(
                  url: widget.url,
                withZoom: true,
                // 是否启用本地缓存
                withLocalStorage: true,
                // 默认状态是否隐藏
                hidden: true,
                // 加载出来网页之前的界面
                initialChild: Container(
                  child: Center(
                    child: CircularProgressIndicator(
                      color: Colors.brown,
                    ),
                  ),
                ),
              )
          )
        ],
      ),
    );
  }

  _appbar(Color backgroundColor, Color backButtonColor) {
    if(widget.hideAppBar ?? false) {
      return Container(
        color: backgroundColor,
        height: 30,
      );
    }
    print("我是火箭🚀🚀🚀🚀🚀🚀🚀🚀");
    return Container(
      child: FractionallySizedBox(
        // 撑满整个布局
        widthFactor: 1,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                BoostNavigator.instance.pop();
              },
              child: Container(
                color: Colors.transparent,
                padding: EdgeInsets.fromLTRB(0, JKSizeFit.topStatusHeight, 0, 0),
                //margin: EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 26,
                ),
              ),
            ),
            Positioned(
                left: 0,
                right: 0,
                child: Center(
                  child: Text(
                    widget.title ?? "",
                    style: TextStyle(
                        color: backButtonColor,
                        fontSize: 20
                    ),
                  ),
                )
            )
          ],
        ),
      ),
    );
  }
}
